package com.mutual.system.user.service.impl;

import java.io.Serializable;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import com.mutual.commom.util.SystemUtil;
import com.mutual.system.areaInfo.pojo.AreaInfo;
import com.mutual.system.areaInfo.service.AreaInfoService;
import com.mutual.system.role.pojo.Role;
import com.mutual.system.role.service.RoleService;
import com.mutual.system.user.dao.UserDao;
import com.mutual.system.user.pojo.User;
import com.mutual.system.user.service.UserService;

@Service("userService")
public class UserServiceImpl implements UserService{

	@Resource
	private UserDao userDao;
	
	@Resource
	private AreaInfoService areaInfoService;
	
	@Resource
	private RoleService roleService;

	@Override
	public void insert(User entity) {
		AreaInfo areaInfo=areaInfoService.selectByPrimaryKey(entity.getAreaId());
		Role role=roleService.selectByPrimaryKey(entity.getRoleId());
		entity.setRoleName(role.getRoleName());
		entity.setAreaCode(areaInfo.getCode());
		entity.setPassword(DigestUtils.md5DigestAsHex(entity.getPhone().getBytes()));
		userDao.insertSelective(entity);
	}

	@Override
	public void updateByPrimaryKey(User entity) {
		AreaInfo areaInfo=areaInfoService.selectByPrimaryKey(entity.getAreaId());
		Role role=roleService.selectByPrimaryKey(entity.getRoleId());
		entity.setRoleName(role.getRoleName());
		entity.setAreaCode(areaInfo.getCode());
		entity.setPassword(DigestUtils.md5DigestAsHex(entity.getPhone().getBytes()));
		userDao.updateByPrimaryKeySelective(entity);
	}

	@Override
	public User selectByPrimaryKey(Serializable entityid) {
		return userDao.selectByPrimaryKey(entityid);
	}

	@Override
	public List<User> selectUserList(Map<String, Object> param) {
		if(param.containsKey("page")){
			int pageNo=SystemUtil.getPageNo(param.get("page"));
			int pageSize=Integer.parseInt(param.get("limit").toString());
			param.put("startNo", (pageNo-1)*pageSize);
			param.put("pageSize", pageSize);
		}
		return userDao.selectUserList(param);
	}

	@Override
	public int selectUserListCount(Map<String, Object> param) {
		return userDao.selectTotalCount(param);
	}

	@Override
	public User userLogin(User user) {
		user.setPassword(DigestUtils.md5DigestAsHex(user.getPassword().getBytes()));
		return userDao.selectUser(user);
	}

	@Override
	public void resetUsersPassword(Map<String, Object> param) {
		userDao.resetUsersPassword(param);
	}

	@Override
	public void updateUsersLock(Map<String, Object> param) {
		userDao.updateUsersLock(param);
	}

	@Override
	public void deleteUserByIds(String[] ids) {
		
	}

	@Override
	public void updateUserPassword(User user) {
		userDao.updateByPrimaryKeySelective(user);
	}
}
